clear all
set more off
cap log close

****************************************************************************
* This do-file extract data from the Read-only LAD files
*	- capital gains, income, dividends and rrsp related variables
* 
* Creates the following Stata files:
*	- capital_income_yyyy.dta
* 	- capital_income_allyears.dta (appended files)
* 
****************************************************************************

do "H:\Lavecchia_7086\to-transfer-jan-2022\RESTAT_Replication_Programs\0_Set_Directories.do"

cap log using "$dir_log\1i_Extract_LossDeductions.log", replace


* Step 1: load the data from LAD read-only files
forvalues year=1982/1983{
clear
use lin__i    using "G:\LAD\LAD_DAL_Allcycle_v3\data\data\Stata\lad`year'.dta"
sort lin__i 
gen year=`year'
save "$dir_data\Capital income years\losses_`year'.dta", replace
}

forvalues year=1984/1985{
clear
use lin__i  nklpyi`year'  using "G:\LAD\LAD_DAL_Allcycle_v3\data\data\Stata\lad`year'.dta"
sort lin__i 
gen year=`year'
rename nklpyi`year'  nklpyi
save "$dir_data\Capital income years\losses_`year'.dta", replace
}

forvalues year=1987/1987{
clear
use lin__i  nklpyi`year' cycgii`year' using "G:\LAD\LAD_DAL_Allcycle_v3\data\data\Stata\lad`year'.dta"
sort lin__i 
gen year=`year'
rename nklpyi`year'  nklpyi
rename cycgii`year' cycgii
save "$dir_data\Capital income years\losses_`year'.dta", replace
}

forvalues year=1988/1990{
clear
use lin__i  nklpyi`year' cycgii`year'  klcbci`year'  using "G:\LAD\LAD_DAL_Allcycle_v3\data\data\Stata\lad`year'.dta"
sort lin__i
gen year=`year'
rename nklpyi`year'  nklpyi
rename cycgii`year' cycgii
rename klcbci`year' klcbci
save "$dir_data\Capital income years\losses_`year'.dta", replace
}

forvalues year=2005/2016{
clear
use lin__i  nklpyi`year' cycgii`year' klcbci`year'  ltplpi`year'  using "G:\LAD\LAD_DAL_Allcycle_v3\data\data\Stata\lad`year'.dta"
sort lin__i
gen year=`year'
rename nklpyi`year'  nklpyi
rename cycgii`year' cycgii
rename klcbci`year' klcbci
rename ltplpi`year' ltplpi
save "$dir_data\Capital income years\losses_`year'.dta", replace
}


* Step 2: append into one file (rename the variables to drop the year portion of the name)

**************** 1982 -- 1999 ****************
clear
*
use "$dir_data\Capital income years\losses_2016.dta"
forvalues i=1982(1)2015{
append using "$dir_data\Capital income years\losses_`i'.dta"
replace klcbci=0 if klcbci==.
replace nklpyi=0 if nklpyi==.
replace ltplpi=0 if ltplpi==.
replace cycgii=0 if cycgii==.
compress
}
gen losses=klcbci+ltplpi+nklpyi
drop klcbci ltplpi nklpyi
*
sort lin__i year
save "$dir_data\losses_all.dta", replace





log close

